<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import { onMounted, ref } from 'vue'
import type { IToolbarConfig } from '@wangeditor-next/editor'
// eslint-disable-next-line ts/ban-ts-comment
// @ts-expect-error
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import type { FormType } from './tuanDetail'
import detailStore from '@/store/modules/NewCacheData'
import { GetTuanDataDetail, GetTuanleaderOption, PostTuanCreateData, PutTuanModifyData } from '@/api/modules/tuangou'
import { GetAllData as GetProductOption } from '@/api/modules/merchandiseControl'
// 引入编辑器的CSS样式
import '@wangeditor/editor/dist/css/style.css'
import { upload } from '@/api/modules/upload.ts'

const router = useRouter()
const route = useRoute()
const detailData = detailStore()
const imgDomain = 'https://img1.eprhan.cc'

const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<FormType>({
  tuanLeaderId: 0,
  tuanTitle: '',
  tuanDesp: '',
  banner: '',
  productId: 0,
  coverPic: '',
  detailPic: '',
  viewCon: 0,
  pubTime: '',
  endTime: '',
  shareTxt: '',
  shareImg: '',
  enable: true,
  vipJson: [],
})

const id = route.query.id as string

const rules = reactive({
  tuanLeaderId: [
    { required: true, message: '请选择团长', trigger: 'blur' },
  ],
  productId: [
    { required: true, message: '请选择要关联的商品', trigger: 'blur' },
  ],
  tuanDesp: [
    { required: true, message: '请输入团购简介', trigger: 'blur' },
  ],
  banner: [
    { required: true, message: '请上传banner图', trigger: 'blur' },
  ],
  coverPic: [
    { required: true, message: '请上传封面图片', trigger: 'blur' },
  ],
  detailPic: [
    { required: true, message: '请上传图文详情', trigger: 'blur' },
  ],
  viewCon: [
    { required: true, message: '请输入浏览人数', trigger: 'blur' },
  ],
  pubTime: [
    { required: true, message: '请选择上架时间', trigger: 'blur' },
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'blur' },
  ],
  shareTxt: [
    { required: true, message: '请填写分享语', trigger: 'blur' },
  ],
  shareImg: [
    { required: true, message: '请上传分享图', trigger: 'blur' },
  ],
  enable: [
    { required: true, message: '请选择是否可用', trigger: 'blur' },
  ],
})

// 图片上传赋值
function handleUploadSuccess(url: string, key: string, index?: number) {
  if (index !== undefined) {
    ruleForm.value.vipJson[index].icon = url
  }
  else {
    ruleForm.value[key] = url
  }
}

// 提交
async function SubmitData(formEl: FormInstance | undefined) {
  if (!formEl) {
    return
  }
  await formEl.validate((valid) => {
    if (valid) {
      const params = { ...ruleForm.value }
      params.coverPic = (params.coverPic as string[]).join(',')
      // console.log(params)

      if (id) {
        // 编辑
        params.tuanInfoId = id
        // console.log(params)

        PutTuanModifyData(params).then((res: any) => {
          if (res.statusCode === 200) {
            ElMessage.success('编辑成功')
            router.push({
              name: 'tuangouTuanLiat',
              query: {
                rxActId: route.query.rxActId,
              },
            })
          }
          else {
            ElMessage.error(`编辑失败。${res.errors}`)
          }
        })
      }
      else {
        // 添加
        PostTuanCreateData(params).then((res: any) => {
          if (res.statusCode === 200) {
            ElMessage.success('添加成功')
            detailData.emptyFormData('tuanForm')
            router.push({
              name: 'tuangouTuanLiat',
              query: {
                rxActId: route.query.rxActId,
              },
            })
          }
          else {
            ElMessage.error(`添加失败。${res.errors}`)
          }
        })
      }
    }
    else {
      ElMessage.error('请检查表单')
    }
  })
}

const OptionList = reactive({
  tuanleaderOption: [],
  productOption: [],
})

// 编辑器实例，必须用 shallowRef，重要！
const editorRef = shallowRef()

// 内容 HTML
const valueHtml = ref('<p>hello</p>')

const toolbarConfig: Partial<IToolbarConfig> = {
  toolbarKeys: [
    'headerSelect',
    'bold',
    'italic',
    'underline',
    'color',
    'bgColor',
    '|',
    'fontSize',
    'fontFamily',
    'lineHeight',
    '|',
    'bulletedList',
    'numberedList',
    '|',
    'insertLink',
    'uploadImage',
    'insertTable',
    'codeBlock',
    '|',
    'undo',
    'redo',
  ],
}

const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      // 自定义上传方法
      async customUpload(file: File, insertFn: (url: string) => void) {
        try {
          const formData = new FormData()
          formData.append('file', file)
          // 调用上传接口
          const res = await upload(formData)

          // 假设接口返回格式为 { url: string }
          const imageUrl = imgDomain + res.data

          // 插入图片
          insertFn(imageUrl)
        }
        catch (error) {
          console.error('图片上传失败', error)
        }
      },
      // 可选：限制文件大小和类型
      maxFileSize: 10 * 1024 * 1024, // 10MB
      allowedFileTypes: ['image/jpeg', 'image/png', 'image/gif'], // 允许的图片类型
    },
  },
}

// 编辑器回调函数
function handleCreated(editor: any) {
  // console.log('created', editor)
  editorRef.value = editor // 记录 editor 实例，重要！
}
function handleChange(editor: any) {
  // console.log('change:', editor.getHtml())
  ruleForm.value.detailPic = editor.getHtml()
  // console.log(ruleForm.value)
}

// 会员配置
function AddCard() {
  // console.log(ruleForm.value.vipJson)

  ruleForm.value.vipJson.push({
    icon: '',
    title: '',
    intro: '',
    href: '',
  })
}

function DeleteCard(index: number) {
  ruleForm.value.vipJson.splice(index, 1)
}

onMounted(async () => {
  if (id) {
    await GetTuanDataDetail(id).then((res: any) => {
      if (res.statusCode === 200) {
        ruleForm.value = res.data
        ruleForm.value.coverPic = (res.data.coverPic as string).split(',')

        valueHtml.value = ruleForm.value.detailPic
      }
    })
  }
  else {
    ruleForm.value = detailData.getFormData('tuanForm')
    // if (ruleForm.value.tuanLeaderId !== 0) {
    //   ruleForm.value.tuanLeaderId = route.query.tuanLeaderId as any
    // }
  }

  // 获取所有卡券
  const ProductOption: any = await GetProductOption()
  if (ProductOption.succeeded) {
    OptionList.productOption = ProductOption.data
    nextTick(() => {
      OptionList.productOption = ProductOption.data
    })
  }

  // 获取团长信息
  const tuanleaderData: any = await GetTuanleaderOption()
  if (tuanleaderData.succeeded) {
    OptionList.tuanleaderOption = tuanleaderData.data
    nextTick(() => {
      OptionList.tuanleaderOption = tuanleaderData.data
    })
  }

  watch(ruleForm, (newValue) => {
    if (!id) {
      detailData.rememberFormData('tuanForm', newValue)
    }
  }, { deep: true })
})

// 组件销毁时，也及时销毁编辑器，重要！
onBeforeUnmount(() => {
  const editor = editorRef.value
  editor.destroy()
})
</script>

<template>
  <div>
    <PageHeader :title="id ? '编辑' : '添加'" />
    <ElForm ref="ruleFormRef" label-position="top" label-width="80px" :rules="rules" :model="ruleForm">
      <PageMain title="基础信息">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="团长" prop="tuanLeaderId">
              <el-select v-model="ruleForm.tuanLeaderId" filterable placeholder="请选择团长">
                <el-option v-for="item in (OptionList.tuanleaderOption as any[])" :key="item.tuanLeaderId" :label="`${item.tuanLeaderId}-${item.name}`" :value="item.tuanLeaderId" />
              </el-select>
            </ElFormItem>
          </ElCol>
          <!-- <ElCol :md="8">
            <ElFormItem label="团购标题（预留）">
              <el-input v-model="ruleForm.tuanTitle" placeholder="请输入团购标题" />
            </ElFormItem>
          </ElCol> -->
          <ElCol :md="8">
            <ElFormItem label="是否可用" prop="enable">
              <el-switch
                v-model="ruleForm.enable"
                active-text="启用"
                inactive-text="停用"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="浏览人数" prop="viewCon">
              <el-input v-model="ruleForm.viewCon" placeholder="请输入浏览人数" type="number" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="上架时间" prop="pubTime">
              <el-date-picker
                v-model="ruleForm.pubTime"
                type="datetime"
                placeholder="请选择上架时间"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="结束时间" prop="endTime">
              <el-date-picker
                v-model="ruleForm.endTime"
                type="datetime"
                placeholder="请选择结束时间"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="商品" prop="productId">
              <el-select v-model="ruleForm.productId" filterable placeholder="请选择商品">
                <el-option v-for="item in (OptionList.productOption as any[])" :key="item.productId" :label="`${item.productId}-${item.productName}`" :value="item.productId" />
              </el-select>
            </ElFormItem>
          </ElCol>
          <ElCol :md="24">
            <ElFormItem label="团购简介" prop="tuanDesp">
              <el-input v-model="ruleForm.tuanDesp" placeholder="请输入团购简介" type="textarea" style="max-width: 550px;" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="24">
            <ElFormItem label="分享语" prop="shareTxt">
              <el-input v-model="ruleForm.shareTxt" placeholder="请输入分享语" type="textarea" style="max-width: 550px;" />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
      <PageMain title="上传图片">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="Banner图" prop="banner">
              <ImageUpload
                width="auto" height="150" :size="5" :url="ruleForm.banner" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'banner')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="分享图" prop="shareImg">
              <ImageUpload
                width="auto" height="150" :size="5" :url="ruleForm.shareImg" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'shareImg')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="24">
            <ElFormItem label="封面图片" prop="coverPic">
              <ImagesUpload
                :size="5" :url="(ruleForm.coverPic as string[])" :max="3" :ext="['jpg', 'png']"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="24">
            <ElFormItem label="图文详情" prop="detailPic">
              <!-- <ImageUpload
                width="auto" height="150" :size="5" :url="ruleForm.detailPic" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'detailPic')"
              /> -->
              <div style=" margin-top: 10px;border: 1px solid #ccc;">
                <Toolbar
                  :editor="editorRef"
                  :default-config="toolbarConfig"
                  mode="default"
                  style="border-bottom: 1px solid #ccc;"
                />
                <Editor
                  v-model="valueHtml"
                  :default-config="editorConfig"
                  mode="default"
                  style="height: 400px; overflow-y: hidden;"
                  @on-created="handleCreated"
                  @on-change="handleChange"
                />
              </div>
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
      <PageMain title="会员配置">
        <div class="mb-5 text-right">
          <el-button type="success" @click="AddCard()">
            添加
          </el-button>
        </div>
        <div class="card-box">
          <el-card v-for="(item, index) in ruleForm.vipJson" :key="index" shadow="hover">
            <el-scrollbar height="400px" :noresize="true">
              <ElFormItem label="标题">
                <el-input v-model="item.title" placeholder="请输入标题" />
              </ElFormItem>
              <ElFormItem label="跳转路径">
                <el-input v-model="item.href" placeholder="请输入跳转路径" />
              </ElFormItem>
              <ElFormItem label="简介">
                <el-input v-model="item.intro" placeholder="请输入简介" />
              </ElFormItem>
              <ElFormItem label="图标">
                <ImageUpload
                  :ext="['jpg', 'png']"
                  :size="5"
                  :url="item.icon"
                  width="auto"
                  @on-success="(url) => handleUploadSuccess(url, 'vipJson', index)"
                />
              </ElFormItem>
            </el-scrollbar>
            <template #footer>
              <div class="text-right">
                <el-button type="danger" @click="DeleteCard(index)">
                  删除
                </el-button>
              </div>
            </template>
          </el-card>
        </div>
      </PageMain>
    </ElForm>
    <div style="height: 80px;" />
    <FixedActionBar>
      <ElButton type="primary" size="large" @click="SubmitData(ruleFormRef)">
        提交
      </ElButton>
    </FixedActionBar>
  </div>
</template>

<style lang="scss" scoped>
.box {
  .title {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
}

.card-box {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-gap: 10px;
}
</style>
